import React, { useEffect, useState } from "react";
import { Button, NavBar, SearchBar } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import styles from "./Index.module.css";
import { Tag } from "antd-mobile";
import instance from "../../api/request";
import { List } from "antd-mobile";
import userFD from "../../hooks/userFD";
function Index() {
  //自定义防抖
  const fd = userFD();
  const nav = useNavigate();
  const [search, setSearch] = useState([]);

  const [keyWord, setKeyWord] = useState("");
  //搜索历史
  const [history, setHistory] = useState([]);

  //热门搜索
  const getSearch = () => {
    instance.get("/api/share/v1/popularSearch").then((res) => {
      console.log(res, "=====热门搜素");
      setSearch(res.data.result);
    });
  };

  const getsou = fd((kw) => {
    instance
      .get("/share/v1/homePageSearch", {
        params: {
          keyWord: kw,
        },
      })
      .then((res) => {
        console.log(res, "=====搜索");
       
        setHistory((prev) => [...prev, kw]);
      });
  });

  useEffect(() => {
    getSearch();
  }, []);

  return (
    <div className={styles.zong}>
      <div className={styles.tou}>
        <NavBar onBack={() => nav(-1)} className={styles.nav}>
          <div className={styles.search}>
            <SearchBar
              value={keyWord}
              //输入框和状态同步，输入更新keyWor
              onChange={(val) => setKeyWord(val)}
              //点击搜索按钮触发搜索
              onSearch={() => getsou(keyWord)}
              className={styles.sousk}
              placeholder="请输入内容"
            />
            <Button
              fill="none"
              className={styles.btn}
              onClick={() => getsou(keyWord)}
            >
              搜索
            </Button>
          </div>
        </NavBar>
      </div>

      <div className={styles.xia}>
        <div className={styles.title}>热门搜索</div>

        <div>
          {search.map((item) => {
            return (
              <Tag className={styles.tag} key={item.id}>
                {item.name}
              </Tag>
            );
          })}
        </div>

        <div className={styles.titlei}>搜索历史</div>
        <div>
          <List>
            {history.map((item, index) => {
              return (
                <List.Item
                  key={index}
                  onClick={() => {
                    setKeyWord(item); // 把该历史关键词回填到输入框
                    getsou(item); //直接触发搜索
                  }}
                >
                  {item}
                </List.Item>
              );
            })}
          </List>
        </div>
      </div>
    </div>
  );
}

export default Index;
